package com.sen.demo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sen.demo.system.entity.User;
import com.sen.demo.system.mapper.UserMapper;
import com.sen.demo.system.vo.LoginUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;


/**
 * @描述: 用户登录实现
 * @作者: 韩宗森
 * @创建时间: 2025年08月21日 15:15
 */
// 加上这个注解 才能被SpringSecurity识别, 才能使用自己用户登录
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 根据用户名查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<>(User.class).eq(User::getUsername, username));

        // 2. 判断用户是否存在
        if (Objects.isNull( user)) {
            throw new RuntimeException("用户不存在");
        }

        // 3. 返回用户信息 UserDetails对象
        return new LoginUser(user);

    }
}
